package com.uinnova.product.eam.service.impl;

import com.alibaba.fastjson.JSON;
import com.binary.framework.bean.annotation.Comment;
import com.uinnova.product.eam.model.EamArtifactVo;
import com.uinnova.product.eam.service.ArchDesignEntranService;
import com.uinnova.product.eam.service.IEamArtifactSvc;
import com.uinnova.product.eam.service.asset.BmConfigSvc;
import com.uinnova.product.eam.dto.ArchDesignEntranConf;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Comment("架构设计入口配置")
@Service
public class ArchDesignEntranServiceImpl implements ArchDesignEntranService {

    //架构设计入口配置
    private static final String ARCH_DESIGN_ENTRAN_CONF = "ARCH_DESIGN_ENTRAN_CONF";

    @Autowired
    private BmConfigSvc bmConfigSvc;
    @Autowired
    private IEamArtifactSvc artifactSvc;

    @Override
    public ArchDesignEntranConf getConf() {
        ArchDesignEntranConf tempConf = new ArchDesignEntranConf();
        tempConf.setDiagram(new ArrayList<>());
        String confStr = bmConfigSvc.getConfigType(ARCH_DESIGN_ENTRAN_CONF);
        if (StringUtils.isBlank(confStr)) {
            return tempConf;
        }
        ArchDesignEntranConf conf = JSON.parseObject(confStr, ArchDesignEntranConf.class);
        if (conf == null) {
            return tempConf;
        }
        if (CollectionUtils.isEmpty(conf.getDiagram())) {
            return tempConf;
        }
        //校验制品id的有效性
        List<Long> artifactIds = conf.getDiagram().stream()
                .map(ArchDesignEntranConf.DiagramConf::getArtifactId)
                .filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(artifactIds)) {
            return tempConf;
        }
        List<EamArtifactVo> artifacts = artifactSvc.queryArtifactByIds(artifactIds);
        if (CollectionUtils.isEmpty(artifacts)) {
            return tempConf;
        }
        Set<Long> exists = artifacts.stream().map(EamArtifactVo::getId).collect(Collectors.toSet());
        List<ArchDesignEntranConf.DiagramConf> diagram = new ArrayList<>();
        for (ArchDesignEntranConf.DiagramConf diagramConf : conf.getDiagram()) {
            if (diagramConf.getArtifactId() == null || !exists.contains(diagramConf.getArtifactId())) {
                continue;
            }
            diagram.add(diagramConf);
        }
        conf.setDiagram(diagram);
        return conf;
    }
}
